package dubbo.learn.core.util;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.lang.Nullable;

public class BeanDefinitionRegistryUtil {

    public static void registerBeanDefinition(BeanDefinitionRegistry beanDefinitionRegistry,
                                BeanDefinition beanDefinition)
            throws BeanDefinitionStoreException{
        String beanName = AnnotationBeanNameGenerator.INSTANCE.generateBeanName(beanDefinition, beanDefinitionRegistry);

        beanDefinitionRegistry.registerBeanDefinition(beanName,beanDefinition);
    }


    public static BeanDefinition getSingleBeanDefinition(ConfigurableListableBeanFactory beanFactory,Class<?> type)
            throws BeanDefinitionStoreException{
        String[] beanNamesForType = beanFactory.getBeanNamesForType(type,true,false);
        if (beanNamesForType == null || beanNamesForType.length == 0) {
            return null;
        }
        if (beanNamesForType.length > 1) {
            throw new RuntimeException();
        }

        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanNamesForType[0]);
        return beanDefinition;
    }
}
